﻿<?php
/**
 * 
 * 通过url获取url指定页面中的内容
 * @param string $url
 * @param int $count
 * @return mixed
 */
function getContents($url, $count=1){
    if(function_exists('curl_init')){
        $ch = curl_init();
        
        //The URL to fetch. This can also be set when initializing a session with curl_init().
        curl_setopt($ch, CURLOPT_URL, $url);
        
        //TRUE to include the header in the output.
        curl_setopt($ch, CURLOPT_HEADER, false);
        
        //TRUE to return the transfer as a string of the return value of curl_exec() 
        //instead of outputting it out directly. 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        //The maximum number of seconds to allow cURL functions to execute. 
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        
        //Returns TRUE on success or FALSE on failure. However, 
        //if the CURLOPT_RETURNTRANSFER option is set, 
        //it will return the result on success, FALSE on failure. 
        $content = curl_exec($ch);
        
        $info = curl_getinfo($ch);
        if(200 != $info['http_code']){
            if($count < 4 ){
                getContents($url, $count+1);
            }else{
                $content = @file_get_contents($url);
            }
        }
    }else{
            $content = @file_get_contents($url);
    }
    return $content;
}



$url = 'www.baidu.com';
$content = getContents($url);
echo $content;
